package com.example.mylibrary.network

import android.content.Context
import com.example.mylibrary.BuildConfig
import com.example.mylibrary.cookies.CookiejarStore
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit

object RetrofitUtil {

    lateinit var retrofit: Retrofit
    lateinit var headerInterceptor: HeaderInterceptor
    const val TIME_OUT = 30000L // 超时时间

    var call: Call<*>? = null

    /**
     * 初始化Retrofit请求
     *
     * isJson 表示是否是json解析,此处处理两中解析,一种json解析一种xml, true 为json解析
     */
    fun init(context: Context, baseUrl: String, isJson: Boolean) {
        // 初始化日志拦截器
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            // 如果是测试版本,开启打印请求日志
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        } else {
            // 如果是正式版本,取消打印请求日志
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE)
        }
        headerInterceptor = HeaderInterceptor()
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(headerInterceptor)                  // 设置请求头拦截
            .addInterceptor(httpLoggingInterceptor)             // 设置日志拦截
            .cookieJar(CookiejarStore())
            .retryOnConnectionFailure(true)
            .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)       // 读取超时
            .writeTimeout(TIME_OUT, TimeUnit.MILLISECONDS)      // 写入超时
            .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)    // 连接超时
            .build()

        // 创建retrofit实例
        val retrofitBuilder = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(MultipleConverterFactory.create())
        retrofit = retrofitBuilder.build()
    }

    // 创建请求接口实例
    fun <T> createService(service: Class<T>): T {
        return retrofit.create(service)
    }

    /**
     *  发送请求
     */
    fun <E> initCall(call: Call<E>, callBack: Callback<E>) {
        initCall(false, call, callBack)
    }

    /**
     *  发送请求,并处理是否取消前一个请求
     */
    fun <E> initCall(cancelBefore: Boolean, call: Call<E>, callBack: Callback<E>) {
        if (cancelBefore) {
            cancelCall()
        }
        call.enqueue(callBack)
        this.call = call
    }

    fun cancelCall() {
        call?.cancel()
        call = null
    }


    fun <E> initObservableCall(observable: Observable<E>, observer: Observer<E>) {
        val observeOn = observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
        initObservableCall(false, observeOn, observer)
    }

    fun <E> initObservableCall(
        cancelBefore: Boolean,
        observable: Observable<E>,
        observer: Observer<E>
    ) {
        observable.subscribe(observer)
    }
}